<?php

namespace App\Models;

use App\Services\AlipayService;
use App\Services\AntchainAtoService;
use App\Services\BaofupayService;
use App\Services\KuaiQianPayService;
use App\Services\CommonService;
use App\Services\EsignService;
use App\Services\OrderService;
use App\Services\AntchainService;
use App\Services\SuningPayService;
use App\Services\WechatService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class OrderRefund extends Model
{
    use HasFactory;
    protected $table = 'sp_order_refund';
    protected $primaryKey = 'id';
    public $timestamps = false;

    const ORDER_REFUND_TYPE_ONLY_REFUND = 1;//仅退款
    const ORDER_REFUND_TYPE_RETURN = 2;//退款退货

    const ORDER_REFUND_SHOP_ALL = 0;//全部
    const ORDER_REFUND_SHOP_NODELIVERY = 1;//商家待收货
    const ORDER_REFUND_NOCHECK = 2;//待审核
    const ORDER_REFUND_SHOP_CHECKED = 3;//商家已审核
    const ORDER_REFUND_SHOP_REFUSE = 4;//商家拒绝
    const ORDER_REFUND_ADMIN_REFUSE = 5;//平台拒绝
    const ORDER_REFUND_SUCCESS = 6;//已退款
    const ORDER_REFUND_CANCEL = 7;//已撤销
    const IS_BACKSTAGE = 8;//已撤销

    //退款接口请求类型
    const ORDER_REFUND_REQUEST_TYPE_XXZ = 1;//小程序
    const ORDER_REFUND_REQUEST_TYPE_DOCKINGT = 2;//对外接口

    const ORDER_REFUND_SINGLE = 1;//单期退款
    const ORDER_REFUND_ALLIN = 2;//全部退款

    const ORDER_REFUND_RESCIND_YES = 1;//解约
    const ORDER_REFUND_RESCIND_NO = 2;//不解约


    const ORDER_REFUND_TYPE_LIST = [
        1 => '仅退款',
        2 => '退款退货',
    ];

    const ORDER_REFUND_STATUS_NAME_LIST = [
        1 => '商家待收货',
        2 => '待审核',
        3 => '平台待审核',
        4 => '商家拒绝',
        5 => '平台拒绝',
        6 => '已退款',
        7 => '已撤销',
    ];

    const ORDER_REFUND_ONLY_REASON_LIST = [
        '不喜欢/不想要了',
        '收到空包裹',
        '未按约定时间发货',
        '快递物流一直未送达',
        '快递物流无跟踪记录',
        '商品破损已拒签'
    ];

    const ORDER_REFUND_RETURN_REASON_LIST = [
        '商品描述不符',
        '商品质量问题',
        '商家发错货',
        '包装/商品破损/裂痕/破损',
        '其他原因'
    ];


    //退款订单列表
    public static function orderRefundList($request,$refund_type,$member_id=''){
        $order_no = !empty($request['order_no'])?$request['order_no']:'';
        $order_status = !empty($request['order_status'])?$request['order_status']:'';
        $refund_status = !empty($request['refund_status'])?$request['refund_status']:'';
        $shopname = !empty($request['shopname'])?$request['shopname']:'';
        $create_time = !empty($request['create_time'])?$request['create_time']:'';
        $page = !empty($request['page'])?$request['page']:1;
        $pageSize = !empty($request['pageSize'])?$request['pageSize']:CommonService::PAGESIZE;
        $whereIn = [];
        $where_status = [];
        $where = [];
        $whereIn1 = [];
        $where_st = [];
        if(!empty($order_no)){
            $where[] = ['o.trade_no','like','%'.$order_no.'%'];
        }
        if(!empty($shopname)){
            $where[] = ['s.shopname','like','%'.$shopname.'%'];
        }
       if (!empty($order_status)&&$order_status==self::IS_BACKSTAGE){
                $where[]= ['or.is_backstage','1'];
           $where_st[] = ['or.refund_status',$refund_status];
        }else if(!empty($refund_status) && !empty($order_status)){
            if($order_status !== self::ORDER_REFUND_SHOP_ALL && $refund_status != $order_status){
                $whereIn = [$order_status,$refund_status];
            }else{
                if($refund_status == self::ORDER_REFUND_SHOP_REFUSE){
                    $whereIn = [self::ORDER_REFUND_SHOP_REFUSE,self::ORDER_REFUND_ADMIN_REFUSE];
                }else{
                    $where_status[] = ['or.refund_status',$refund_status];
                }
            }
        }elseif (!empty($refund_status) && empty($order_status)){
            if($refund_status == self::ORDER_REFUND_SHOP_REFUSE){
                $whereIn = [self::ORDER_REFUND_SHOP_REFUSE,self::ORDER_REFUND_ADMIN_REFUSE];
                $whereIn1 = [self::ORDER_REFUND_SHOP_REFUSE,self::ORDER_REFUND_ADMIN_REFUSE];
            }else{
                $where_status[] = ['or.refund_status',$refund_status];
                $where_st[] = ['or.refund_status',$refund_status];
            }
        }elseif (empty($refund_status) && !empty($order_status)){
            if($order_status == self::ORDER_REFUND_SHOP_REFUSE){
                $whereIn = [self::ORDER_REFUND_SHOP_REFUSE,self::ORDER_REFUND_ADMIN_REFUSE];
            }else{
                $where_status[] = ['or.refund_status',$order_status];
            }
        }

        if(!empty($member_id)){
            $where[] = ['o.seller_id',$member_id];
        }
        if(!empty($create_time)){
            $time_data = searchTime($create_time);
            $begin_time = $time_data['begin_time'];
            $end_time = $time_data['end_time'];
            $where[] = ['or.create_time','>=',$begin_time];
            $where[] = ['or.create_time','<=',$end_time];
        }
        $where[] = ['or.refund_type',$refund_type];
        $where_search = array_merge($where,$where_status);
        $orderList = OrderRefund::from('sp_order_refund as or')
            ->leftjoin('sp_order_2 as o','or.order_id','o.id')
            ->leftjoin('sp_member_2 as m','o.uid','m.id')
            ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
            ->leftjoin('sp_shop_user_2 as s','s.member_id','o.seller_id')
            ->select('or.id','or.order_id','m.cert_name','o.trade_no','or.create_time','s.shopname',
                'og.goods_title','og.imgurl','og.setmeal_title','o.amount','or.refund_amount',
                'or.deduct_amount','or.paid_total_rent','og.setmeal_foregift','o.foregift_deduct',
                'o.foregift','or.refund_type','or.refund_reason','or.refund_status','or.refuse_reason')->where($where_search);
        $whereIn && $orderList->whereIn('or.refund_status',$whereIn);
        $orderList->orderBy('or.id','desc');
        $list = obToArray($orderList->paginate($pageSize));
        // dd($list);
        if(!empty($where_st)){
            $where = array_merge($where,$where_st);
        }
        if(!empty($whereIn1)){
            $order_count = OrderRefund::from('sp_order_refund as or')->where($where)->whereIn('or.refund_status',$whereIn1)->leftjoin('sp_order_2 as o','or.order_id','o.id')->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')->leftjoin('sp_shop_user_2 as s','s.member_id','o.seller_id')->select('or.refund_status',DB::raw('count(*) as count'))->groupBy(['or.refund_status'])->get();
        }else{
            $order_count = OrderRefund::from('sp_order_refund as or')
                ->leftjoin('sp_order_2 as o','or.order_id','o.id')
                ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
                ->leftjoin('sp_shop_user_2 as s','s.member_id','o.seller_id')
                ->select('or.refund_status',DB::raw('count(*) as count'))->groupBy(['or.refund_status'])->get();
        }
        $order_count = obToArray($order_count);
        $count['order_total_count'] = 0;
        $count['user_apply_refund'] = 0;
        $count['admin_nocheck'] = 0;
        $count['refund_finish'] = 0;
        $count['refund_rufuse'] = 0;
        $count['refund_close'] = 0;
        $count['refund_backstage'] = OrderRefund::from('sp_order_refund as or')
            ->leftjoin('sp_order_2 as o','or.order_id','o.id')
            ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
            ->leftjoin('sp_shop_user_2 as s','s.member_id','o.seller_id')
            ->where('or.is_backstage',1)->count();
        if(!empty($order_count)){
            foreach ($order_count as $item){
                $count['order_total_count'] += $item['count'];
                if($item['refund_status'] == self::ORDER_REFUND_NOCHECK){
                    $count['user_apply_refund'] = $item['count'];
                }
                if($item['refund_status'] == self::ORDER_REFUND_SHOP_CHECKED){
                    $count['admin_nocheck'] = $item['count'];
                }
                if($item['refund_status'] == self::ORDER_REFUND_SUCCESS){
                    $count['refund_finish'] = $item['count'];
                }
                if($item['refund_status'] == self::ORDER_REFUND_SHOP_REFUSE || $item['refund_status'] == self::ORDER_REFUND_ADMIN_REFUSE){
                    $count['refund_rufuse'] += $item['count'];
                }
            }
        }
        $list['count']=$count;
        return $list;
    }


    //订单退款
    public static function orderRefund($order, $lease_id, $request_type, $refund_num, $is_rescind = self::ORDER_REFUND_RESCIND_YES)
    {
        if (!empty($order)) {
            $miniId = $order['mini_id'];

            if ($order['pay_type'] == OrderLease::LEASE_PAY_TYPE_ANTCHAIN) {//智能合同代扣
                if ($order['sign_no']) {
                    AntchainAtoService::cancelWithholdPlan($order['trade_no']);
                    AntchainAtoService::closeOrder($order['trade_no']);
                    AntchainAtoService::asyncUnbindConfirm($order['trade_no'], "AGREE", null, 0, null);
                }
                if (!empty($lease_id)) {
                    $res_count = 0;
                    foreach ($lease_id as $k => $v) {
                        $order_lease = OrderLease::where([['id', $v], ['order_id', $order['order_id']]])
                            ->select('id', 'order_id', 'which_period', 'rent', 'paid_rent', 'settle_type', 'pay_type', 'pay_time', 'out_order_no', 'alipay_trade_no', 'status')->first();
                        $order_lease = obToArray($order_lease);
                        if (empty($order_lease)) {
                            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '账单不存在', 'data' => []];
                        }
                        $transaction_fee=0;
                        if($order_lease['which_period']==1){
                            $transaction_fee=OrderGoods::query()->where('order_id',$order['order_id'])->value('transaction_fee');
                        }

                        if($order_lease['pay_type']== OrderLease::LEASE_PAY_TYPE_ANTCHAIN) {
                            AntchainAtoService::createWithholdRefund($order['trade_no'],1,bcmul($order_lease['rent']-$transaction_fee,100));
                        }
                        if ($order_lease['pay_type'] == OrderLease::PAY_TYPE_YIFUBAO) {

                            $out_request_no = $order['trade_no'] . $order_lease['id'] . time();

                            $param['refundOrderNo'] = $out_request_no;
                            $param['origMerchantOrderNo'] = $order_lease['alipay_trade_no'];
                            $param['origOrderTime'] = $order_lease['pay_time'];
                            $param['refundAmount'] = bcmul($order_lease['rent']-$transaction_fee, 100);
                            $param['operator'] = $order['shopname'];
                            $param['refundReason'] = $order['refund_reason'];

                            $KuaiQianPayService = new KuaiQianPayService();
                            $refund_res = $KuaiQianPayService->refund($param);
                            if (!$refund_res) {
                                return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '宝付' . $refund_res['responseMsg'], 'data' => []];
                            }
                            $remarks = $order['shopname'] . '|' . $order['goods_title'] . '|第' . $order_lease['which_period'] . '期退款';
                            $order_trans = ShopTrans::getOrderRefundTrans($order, $order_lease);
                            if (!empty($order_trans) && $refund_res) {
                                ShopTrans::addOrderTrans($order, $order_trans['settle_amount'], $order_trans['service_fee'], $order_lease['out_order_no'], $remarks, $order_lease['id'], $order_trans['fee_rate'], $order_trans['fixed_fee'], $order_trans['trans_detail'], ShopTrans::ORDER_TRANS_TYPE_REFUND);
                            }

                        }

                        if ($order_lease['pay_type'] == OrderLease::LEASE_PAY_TYPE_WECHAT) {

                            $transpayAmout = OrderLease::where([['out_order_no', $order_lease['out_order_no']], ['order_id', $order['order_id']]])
                                ->sum('paid_rent');
                            $refund_res = WechatService::refund($order['trade_no'], $order_lease['out_order_no'], $order_lease['paid_rent'] * 100, $transpayAmout * 100);
                            if ($refund_res['result_code'] != 'SUCCESS') {
                                return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '微信支付' . $refund_res['err_code_des'], 'data' => []];
                            }

                            $remarks = $order['shopname'] . '|' . $order['goods_title'] . '|第' . $order_lease['which_period'] . '期退款';
                            $order_trans = ShopTrans::getOrderRefundTrans($order, $order_lease);
                            if (!empty($order_trans) && $refund_res) {
                                ShopTrans::addOrderTrans($order, $order_trans['settle_amount'], $order_trans['service_fee'], $order_lease['out_order_no'], $remarks, $order_lease['id'], $order_trans['fee_rate'], $order_trans['fixed_fee'], $order_trans['trans_detail'], ShopTrans::ORDER_TRANS_TYPE_REFUND);
                            }
                        }

                    }

                }

                if (!empty($lease_id)) {
                    //判断是否有主动支付多期合并支付退款
                    $lease_arr = OrderLease::whereIn('id', $lease_id)->select('alipay_trade_no')->get();
                    $lease_arr = obToArray($lease_arr);
                    $repeat_lease = FetchRepeatMemberInArray($lease_arr);
                    $repeat_lease_tradeno = 1;
                    if (!empty($repeat_lease)) {
                        $repeat_lease_tradeno = $repeat_lease[0]['alipay_trade_no'];
                    }
                    foreach ($lease_id as $k => $v) {
                        $order_lease = OrderLease::where([['id', $v], ['order_id', $order['order_id']]])
                            ->select('id', 'order_id', 'which_period', 'rent', 'paid_rent', 'settle_type', 'out_order_no', 'alipay_trade_no', 'status')->first();
                        $order_lease = obToArray($order_lease);
                        $transaction_fee=0;
                        if($order_lease['which_period']==1){
                            $transaction_fee=OrderGoods::query()->where('order_id',$order['order_id'])->value('transaction_fee');
                        }
                        if (!empty($order_lease)) {
                            if ($order_lease['alipay_trade_no'] == $repeat_lease_tradeno) { //主动支付多期合并支付退款
                                $order_lease = OrderLease::where([['alipay_trade_no', $repeat_lease_tradeno], ['order_id', $order['order_id']]])->select('id', 'order_id', 'which_period', 'rent', 'paid_rent', 'settle_type', 'out_order_no', 'alipay_trade_no', 'status')->get();
                                $order_lease = obToArray($order_lease);
                                $paid_rent = array_sum(array_column($order_lease, 'rent'));
                                $refund_data['amount'] = sprintf("%.2f", $paid_rent-$transaction_fee);
                                $refund_data['outTradeNo'] = $order_lease[0]['out_order_no'];
                                $refund_data['tradeNo'] = $order_lease[0]['alipay_trade_no'];
                                $refund_res = AlipayService::alipayRefund($miniId, $refund_data);
                                if ($refund_res['status']) { //退款成功
                                    foreach ($order_lease as $key => $val) {
                                        $remarks = $order['shopname'] . '|' . $order['goods_title'] . '|第' . $val['which_period'] . '期退款';
                                        $order_trans = ShopTrans::getOrderRefundTrans($order, $val);
                                        if (!empty($order_trans) && $order_trans['settle_amount'] != 0) {
                                            ShopTrans::addOrderTrans($order, $order_trans['settle_amount'], $order_trans['service_fee'], $refund_res['data']['trade_no'], $remarks, $val['id'], $order_trans['fee_rate'], $order_trans['fixed_fee'], $order_trans['trans_detail'], ShopTrans::ORDER_TRANS_TYPE_REFUND);
                                        }
                                    }
                                }else{
                                    return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'支付宝支付'.$refund_res['msg'],'data'=>[]];
                                }
                            } else {
                                $refund_data['amount'] =bcsub($order_lease['rent'],$transaction_fee,2);
                                $refund_data['outTradeNo'] = $order_lease['out_order_no'];
                                $refund_data['tradeNo'] = $order_lease['alipay_trade_no'];
                                $refund_res = AlipayService::alipayRefund($miniId, $refund_data);
                                if ($refund_res['status']) { //退款成功
                                    $remarks = $order['shopname'] . '|' . $order['goods_title'] . '|第' . $order_lease['which_period'] . '期退款';
                                    $order_trans = ShopTrans::getOrderRefundTrans($order, $order_lease);
                                    if (!empty($order_trans) && $order_trans['settle_amount'] != 0) {
                                        ShopTrans::addOrderTrans($order, $order_trans['settle_amount'], $order_trans['service_fee'], $refund_res['data']['trade_no'], $remarks, $order_lease['id'], $order_trans['fee_rate'], $order_trans['fixed_fee'], $order_trans['trans_detail'], ShopTrans::ORDER_TRANS_TYPE_REFUND);
                                    }
                                }else{
                                    return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'支付宝支付'.$refund_res['msg'],'data'=>[]];
                                }
                            }
                        } else {
                            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '账单不存在', 'data' => []];
                        }
                    }
                }

                if (!empty($order['rights_auth_no'] && $order['alipay_trade_no']) && $order['status'] <= OrderService::ORDER_STATUS_PAY_SUCCESS) {//解冻预授权，作废合同
                    $alipay_data['alipayTradeNo'] = $order['alipay_trade_no'];
                    $alipay_data['authNo'] = $order['rights_auth_no'];
                    $prequery = AlipayService::alipayPreQuery($miniId, $alipay_data);
                    if ($prequery['status']) {
                        $rest_amount = $prequery['data']['rest_amount'];//订单总共剩余的冻结金额
                        if ($rest_amount > 0) { //冻结金额大于0  执行解冻操作
                            $thaw_data['amount'] = $rest_amount;
                            $thaw_data['authNo'] = $order['rights_auth_no'];
                            $thaw_query = AlipayService::alipayPreThaw($miniId, $thaw_data);
                            if ($thaw_query['status'] && $thaw_query['data']['code'] == AlipayService::ALIPAY_SUCCESS_CODE) { //解冻成功
                                //查找扣款失败未履约的订单
                                $log = OtherWithholdLog::where(['order_no' => $order['trade_no'], 'status' => 0])->whereIn('pay_type', [OtherWithholdLog::PAY_TYPE_ZM, OtherWithholdLog::PAY_TYPE_MANUAL_ZM])
                                    ->groupBy('out_trade_no')
                                    ->get();
                                foreach ($log as $value) {
                                    $orderData = [
                                        'orderId' => $value['order_no'],
                                        'outTradeNo' => $value['out_trade_no'],
                                        'tradeNo' => $value['trade_no'],
                                        'status' => 'CLOSED',
                                    ];
                                    AlipayService::orderInfo($miniId, $orderData);
                                }
                            }
                        }
                    }
                }

                if ($is_rescind == self::ORDER_REFUND_RESCIND_YES) {//退款解约

                    if (!$order['sign_no'] && $order['flow_id']) {
                        AntchainService::paytradeCancel($order['flow_id']);
                    }
                    DB::beginTransaction();
                    if ($refund_num == self::ORDER_REFUND_SINGLE) {//单期退款
                        $res = Order::where('id', $order['order_id'])->update(['status' => OrderService::ORDER_STATUS_PART_REFUND]);
                    } else {
                        $res = Order::where('id', $order['order_id'])->update(['status' => OrderService::ORDER_STATUS_REFUND_SUCCESS]);
                    }
                    $lease_res = OrderLease::whereIn('id', $lease_id)->update(['status' => OrderLease::ORDER_LEASE_STATUS_REFUNDED, 'refund_time' => date('Y-m-d H:i:s')]);

                    if ($lease_res && $res) {
                        if ($request_type == self::ORDER_REFUND_REQUEST_TYPE_XXZ) {
                            OrderRefund::where('order_id', $order['order_id'])->update(['refund_status' => self::ORDER_REFUND_SUCCESS]);
                        }
                        DB::commit();
                        return ['status' => CommonService::HTTP_CODE_SUCCESS, 'msg' => '退款成功', 'data' => []];
                    } else {
                        DB::rollBack();
                        return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '退款状态更新失败', 'data' => []];
                    }
                } else {
                    $lease_res = OrderLease::whereIn('id', $lease_id)->update(['status' => OrderLease::ORDER_LEASE_STATUS_REFUNDED, 'refund_time' => date('Y-m-d H:i:s')]);
                    if ($lease_res) {
                        return ['status' => CommonService::HTTP_CODE_SUCCESS, 'msg' => '退款成功', 'data' => []];
                    } else {
                        return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '退款成功状态更新失败', 'data' => []];
                    }
                }
            } else {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }

        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
    }





    //关闭订单退款
    public static function orderCloseAndRefund($order,$username){
        if(!empty($order)){
            if ($order['pay_type'] == OrderLease::LEASE_PAY_TYPE_ANTCHAIN){//智能合同代扣

                        $order_leases = OrderLease::where('order_id',$order['order_id'])
                            ->where('status',OrderLease::ORDER_LEASE_STATUS_PAID)
                            ->select('id','order_id','which_period','rent','paid_rent','settle_type','pay_type','pay_time','out_order_no','alipay_trade_no','status')->get();
                        $order_leases = obToArray($order_leases);
                    if(empty($order_leases)){
                        return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'账单不存在','data'=>[]];
                    }
                    $lease_id=[];

                    foreach ($order_leases as $k=>$order_lease){
                        $lease_id[] = $order_lease['id'];
                        $order_trans = ShopTrans::getOrderRefundTrans($order,$order_lease);
                        if(!empty($order_trans) && isset($order_trans['settle_amount'])){
                            $deduct_amount += $order_trans['settle_amount'];
                        }
                        $transaction_fee=0;
                        if($order_lease['which_period']==1){
                            $transaction_fee=OrderGoods::query()->where('order_id',$order['order_id'])->value('transaction_fee');
                        }

                        if($order_lease['pay_type']== OrderLease::LEASE_PAY_TYPE_ANTCHAIN) {
                           AntchainAtoService::createWithholdRefund($order['trade_no'],1,bcmul($order_lease['rent']-$transaction_fee,100));
                        }
                            if($order_lease['pay_type']== OrderLease::PAY_TYPE_YIFUBAO){

                            $out_request_no = $order['trade_no'].$order_lease['id'].time();

                            $param['refundOrderNo']=$out_request_no;
                            $param['origMerchantOrderNo']=$order_lease['alipay_trade_no'];
                            $param['origOrderTime']=$order_lease['pay_time'];
                            $param['refundAmount']=bcmul($order_lease['rent']-$transaction_fee,100);
                            $param['operator']=$order['shopname'];
                            $param['refundReason']=$order['refund_reason'];

                            $KuaiQianPayService=new KuaiQianPayService();
                            $refund_res=$KuaiQianPayService->refund($param);
                            if(!$refund_res){
                                return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'宝付'.$refund_res['responseMsg'],'data'=>[]];
                            }
                            $remarks = $order['shopname'].'|'.$order['goods_title'].'|第'.$order_lease['which_period'].'期退款';
                            $order_trans = ShopTrans::getOrderRefundTrans($order,$order_lease);
                            if(!empty($order_trans)&&$refund_res){
                                ShopTrans::addOrderTrans($order,$order_trans['settle_amount'],$order_trans['service_fee'],$order_lease['out_order_no'],$remarks,$order_lease['id'],$order_trans['fee_rate'],$order_trans['fixed_fee'],$order_trans['trans_detail'],ShopTrans::ORDER_TRANS_TYPE_REFUND);
                            }

                        }

                        if($order_lease['pay_type']== OrderLease::LEASE_PAY_TYPE_WECHAT){

                            $transpayAmout = OrderLease::where([['out_order_no',$order_lease['out_order_no']],['order_id',$order['order_id']]])
                                ->sum('paid_rent');
                            $refund_res=WechatService::refund($order['trade_no'],$order_lease['out_order_no'],$order_lease['paid_rent']*100,$transpayAmout*100);
                            if($refund_res['result_code']!='SUCCESS'){
                                return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'微信支付'.$refund_res['err_code_des'],'data'=>[]];
                            }

                            $remarks = $order['shopname'].'|'.$order['goods_title'].'|第'.$order_lease['which_period'].'期退款';
                            $order_trans = ShopTrans::getOrderRefundTrans($order,$order_lease);
                            if(!empty($order_trans)&&$refund_res){
                                ShopTrans::addOrderTrans($order,$order_trans['settle_amount'],$order_trans['service_fee'],$order_lease['out_order_no'],$remarks,$order_lease['id'],$order_trans['fee_rate'],$order_trans['fixed_fee'],$order_trans['trans_detail'],ShopTrans::ORDER_TRANS_TYPE_REFUND);
                            }
                        }

                    }

                //判断是否有主动支付多期合并支付退款
                $lease_arr = OrderLease::whereIn('id',$lease_id)->where('pay_type',OrderLease::LEASE_PAY_TYPE_PREPAYMENT)->select('alipay_trade_no')->get();
                $lease_arr = obToArray($lease_arr);

                if(!empty($lease_id)&&$lease_arr){

                    foreach ($lease_id as $k=>$v){
                        $repeat_lease = FetchRepeatMemberInArray($lease_arr);
                        $repeat_lease_tradeno = 1;
                        if(!empty($repeat_lease)){
                            $repeat_lease_tradeno = $repeat_lease[0]['alipay_trade_no'];
                        }
                        $order_lease = OrderLease::where([['id',$v],['order_id',$order['order_id']]])
                            ->select('id','order_id','which_period','rent','paid_rent','settle_type','out_order_no','alipay_trade_no','status')->first();
                        $order_lease = obToArray($order_lease);
                        if(!empty($order_lease)){
                            $transaction_fee=0;
                            if($order_lease['which_period']==1){
                                $transaction_fee=OrderGoods::query()->where('order_id',$order['order_id'])->value('transaction_fee');
                            }
                            if($order_lease['alipay_trade_no'] == $repeat_lease_tradeno){ //主动支付多期合并支付退款
                                $order_lease = OrderLease::where([['alipay_trade_no',$repeat_lease_tradeno],['order_id',$order['order_id']]])->select('id','order_id','which_period','rent','paid_rent','settle_type','out_order_no','alipay_trade_no','status')->get();
                                $order_lease = obToArray($order_lease);
                                $paid_rent = array_sum(array_column($order_lease,'rent'));
                                $refund_data['amount'] = sprintf("%.2f", $paid_rent-$transaction_fee);
                                $refund_data['outTradeNo'] = $order_lease[0]['out_order_no'];
                                $refund_data['tradeNo'] = $order_lease[0]['alipay_trade_no'];
                                $refund_res = AlipayService::alipayRefund($order['mini_id'],$refund_data);
                                if($refund_res['status']){ //退款成功
                                    foreach ($order_lease as $key => $val){
                                        $remarks = $order['shopname'].'|'.$order['goods_title'].'|第'.$val['which_period'].'期退款';
                                        $order_trans = ShopTrans::getOrderRefundTrans($order,$val);
                                        if(!empty($order_trans) && $order_trans['settle_amount'] !=0){
                                            ShopTrans::addOrderTrans($order,$order_trans['settle_amount'],$order_trans['service_fee'],$refund_res['data']['trade_no'],$remarks,$val['id'],$order_trans['fee_rate'],$order_trans['fixed_fee'],$order_trans['trans_detail'],ShopTrans::ORDER_TRANS_TYPE_REFUND);
                                        }
                                    }
                                }else{
                                    return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'支付宝支付'.$refund_res['msg'],'data'=>[]];
                                }
                            }else{
                                $refund_data['amount'] = bcsub($order_lease['rent'],$transaction_fee,2);
                                $refund_data['outTradeNo'] = $order_lease['out_order_no'];
                                $refund_data['tradeNo'] = $order_lease['alipay_trade_no'];
                                $refund_res = AlipayService::alipayRefund($order['mini_id'],$refund_data);
                                if($refund_res['status']){ //退款成功
                                    $remarks = $order['shopname'].'|'.$order['goods_title'].'|第'.$order_lease['which_period'].'期退款';
                                    $order_trans = ShopTrans::getOrderRefundTrans($order,$order_lease);
                                    if(!empty($order_trans) && $order_trans['settle_amount'] !=0){
                                        ShopTrans::addOrderTrans($order,$order_trans['settle_amount'],$order_trans['service_fee'],$refund_res['data']['trade_no'],$remarks,$order_lease['id'],$order_trans['fee_rate'],$order_trans['fixed_fee'],$order_trans['trans_detail'],ShopTrans::ORDER_TRANS_TYPE_REFUND);
                                    }
                                }else{
                                    return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'支付宝支付'.$refund_res['msg'],'data'=>[]];
                                }
                            }
                        }else{
                            return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'账单不存在','data'=>[]];
                        }
                    }
                }


                    DB::beginTransaction();

                $paid_ren = OrderLease::where([['order_id',$order['order_id']],['status',OrderLease::ORDER_LEASE_STATUS_PAID]])->sum('paid_rent');

                $data['order_id'] = $order['order_id'];
                $data['user_mobile'] = $order['mobile'];
                $data['refund_amount'] = $paid_ren;
                $data['deduct_amount'] = $deduct_amount;
                $data['paid_total_rent'] = array_sum(array_column($order_lease,'paid_rent'));
                $data['refund_type'] = OrderRefund::ORDER_REFUND_TYPE_ONLY_REFUND;
                $data['refund_reason'] = '后台手动关闭订单并退款';
                $data['refund_desc'] =$username.'操作退款';
                $data['refund_image'] = '';
                $data['is_backstage'] =1;
                $data['refund_order_status'] = $order['status'];
                $data['refund_status'] = OrderRefund::ORDER_REFUND_SUCCESS;
                $data['create_time'] = date('Y-m-d H:i:s');
                $data['update_time'] = date('Y-m-d H:i:s');
                if(OrderRefund::where('order_id',$order['order_id'])->wherein('refund_status',[OrderRefund::ORDER_REFUND_NOCHECK,OrderRefund::ORDER_REFUND_SHOP_CHECKED,OrderRefund::ORDER_REFUND_SHOP_REFUSE,OrderRefund::ORDER_REFUND_ADMIN_REFUSE,OrderRefund::ORDER_REFUND_CANCEL])->count() > 0){
                    $add_re = OrderRefund::where('order_id',$order['order_id'])->update($data);
                }else {
                    $add_re = OrderRefund::insert($data);
                }
                    $res = Order::where('id',$order['order_id'])->update(['status'=>OrderService::ORDER_STATUS_REFUND_SUCCESS]);
                    $lease_res = OrderLease::whereIn('id',$lease_id)->update(['status'=>OrderLease::ORDER_LEASE_STATUS_REFUNDED,'refund_time'=>date('Y-m-d H:i:s')]);

                    if($lease_res && $res){
                        OrderRefund::where('order_id', $order['order_id'])->update(['refund_status' => self::ORDER_REFUND_SUCCESS]);
                        DB::commit();
                        return ['status'=>CommonService::HTTP_CODE_SUCCESS,'msg'=>'退款成功','data'=>[]];
                    }else{
                        DB::rollBack();
                        return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'退款状态更新失败','data'=>[]];
                    }

            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }

        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
    }



}
